package com.shanshan.wheel.rpc.common.remoting.transport.clent;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 用于管理连接的类
 * @ClassName ChannelProvider
 * @Author 山山大魔王
 * @Date 2022/9/5 12:10
 * @Version 1.0
 */
@Component
@Slf4j
public class ChannelProvider {

    // key 为提供方的地址
    private Map<String, Channel> channelMap;

    public ChannelProvider() {
        channelMap = new ConcurrentHashMap<>();
    }
    // 获取地址对应的通道
    public Channel get(InetSocketAddress inetSocketAddress){
        String key = inetSocketAddress.toString();
        if(channelMap.containsKey(key)){
            Channel channel = channelMap.get(key);
            // 判断该连接是否可用
            if(channel != null && channel.isActive()){
                return channel;
            }else {
                // 不可用将其删除
                channelMap.remove(channel);
            }
        }
        return null;
    }

    /**
     * 设置通道
     * @param inetSocketAddress
     * @param channel
     */
    public void set(InetSocketAddress inetSocketAddress, Channel channel){
        String key = inetSocketAddress.toString();
        channelMap.put(key, channel);
    }

    /**
     * 删除通道
     * @param inetSocketAddress
     */
    public void remove(InetSocketAddress inetSocketAddress){
        String key = inetSocketAddress.toString();
        if(channelMap.containsKey(key)){
            channelMap.remove(key);
        }
    }
}
